package datasource

import (
	"log"
	"sync"
	"testhttp/conf"

	_ "github.com/go-sql-driver/mysql"
	_ "github.com/mattn/go-sqlite3"
	"xorm.io/xorm"
)

// 数据库单例 dbhelper.go
var (
	masterEngine *xorm.Engine
	lock         sync.Mutex
	// slaveEngine  *xorm.Engine
)

func InstanceMaster() *xorm.Engine {
	if masterEngine != nil {
		return masterEngine
	}

	lock.Lock()
	defer lock.Unlock()

	if masterEngine != nil {
		return masterEngine
	}

	// c := conf.MasterDbConf
	// driverSource := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8",
	// 	c.User, c.Pwd, c.Host, c.Port, c.DbName)
	// fmt.Println(driverSource)

	masterEngine, err := xorm.NewEngine(conf.DriverName, conf.DbName)
	if err != nil {
		log.Fatal("dbhelper.DbInstanceMaster err:", err)
		return nil
	}

	// DEBUG 模式，打印全部sql, 帮助对比 orm 与 sql 执行对照关系
	masterEngine.ShowSQL(false)
	// masterEngine.SetTZLocation(conf.SysTimeLocation)

	return masterEngine
}
